package com.mhxy.util;

import cn.hutool.core.io.FileUtil;
import com.mhxy.constant.ParamConstants;
import com.mhxy.entity.FindPicResult;
import com.sun.jna.platform.win32.WinDef;
import lombok.extern.slf4j.Slf4j;
import org.opencv.core.Rect;

import java.io.File;

@Slf4j
public class FuzzyRectPicUtil {
    public static boolean findAndClickRandom(WinDef.HWND hwnd_0, String destImagePath, Rect rect, int maxTimes, double sim) throws Exception {
        // 找图需要用主程序的句柄，截图才能全
        FindPicResult pic = findPic(hwnd_0, destImagePath, rect, maxTimes, sim);
        if (!pic.isFinded()) {
            return false;
        }
        // 点击需要用子程序的句柄
        return MouseUtil.lClickRandom(hwnd_0, pic.getPicX(), pic.getPicY());
    }
    public static boolean findAndClickRandom(WinDef.HWND hwnd_0, String destImagePath, Rect rect, int maxTimes) throws Exception {
        return findAndClickRandom(hwnd_0, destImagePath, rect, maxTimes, ParamConstants.SIMILARITY);
    }

    /**
     * 在矩形区域内循环找单图
     *
     * @return
     */
    public static FindPicResult findPic(WinDef.HWND hwnd, String destImagePath, Rect matchRect, int times, double sim) throws Exception {
        times = times <= 0 ? ParamConstants.FIND_MAX_TIMES : times;
        FindPicResult pic = null;
        try {
            for (int i = 0; i < times; i++) {
                String srcImagePath = null;
                try {
                    srcImagePath = FuzzyPicUtil.getHwndPic(hwnd);
                    pic = OpencvUtil.findByRect(srcImagePath, destImagePath, matchRect, sim);
                    if (pic.isFinded()) {
                        return pic;
                    }
                    log.warn("区域找图，第[{}]次未找到!", i + 1);
                    ThreadUtil.sleep2();
                } catch (Throwable e) {
                    log.error("区域找图失败:", e);
                } finally {
                    // 删除临时图片
                    if (srcImagePath != null) {
                        FileUtil.del(srcImagePath);
                    }
                }
            }
        } catch (Exception e) {
            log.error("区域找图对比图片错误", e);
            throw e;
        }

        return pic;
    }
}
